package com.lg.cms.controller.admin.permmission;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.cms.dto.PermissionDTO;
import com.lg.cms.entity.Role;
import com.lg.cms.entity.SuperUser;
import com.lg.cms.service.RolePermissionService;
import com.lg.cms.service.RoleService;
import com.lg.cms.utils.SubjectUtil;
import com.lg.cms.vo.LayerTableVO;
import com.lg.cms.vo.admin.PermissionVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 角色管理
 * @Author: wuyuhang
 * @create: 2020-10-03 10:53
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    RolePermissionService rolePermissionService;

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("/list")
    public String list(Model model, HttpServletRequest request){
        model.addAttribute("request", request);
        model.addAttribute("user", SubjectUtil.getSuperUser());
        model.addAttribute("roleList", roleService.list());
        return "/admin/authority_management/roleCategory";
    }

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("/get_list")
    @ResponseBody
    public LayerTableVO<Role> getList(@RequestParam("page") Integer current, @RequestParam("limit") Integer limit){
        Page<Role> page = new Page<>(current, limit);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        roleService.page(page, wrapper);
        LayerTableVO<Role> vo = new LayerTableVO<>();
        vo.setMsg("");
        vo.setCount(page.getTotal());
        vo.setCode(0);
        vo.setData(page.getRecords());

        return vo;
    }

    /**
     * 新增角色
     * @param role
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public R<?> add(Role role){
        if(!role.checkData()){
            return R.failed("请输入必填信息");
        }
        boolean result = roleService.save(role);
        if(!result){
            return R.failed("创建角色失败");
        }
        return R.ok(role);
    }

    /**
     * 根据id获取角色信息
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    @ResponseBody
    public R<?> getById(@PathVariable("id") Integer id){
        Role role = roleService.getById(id);
        if(role == null){
            return R.failed("角色不存在");
        }
        return R.ok(role);

    }

    /**
     * 编辑角色信息
     * @param role
     * @return
     */
    @PutMapping("/update")
    @ResponseBody
    public R<?> update(Role role){
        if(role.getId() == null){
            return R.failed("id不能为空");
        }
        if(!role.checkData()){
            return R.failed("请输入必填信息");
        }
        Role oldRole = roleService.getById(role.getId());
        if(oldRole == null){
            return R.failed("角色不存在");
        }
        oldRole.setName(role.getName());
        oldRole.setDescription(role.getDescription());
        boolean result = roleService.updateById(oldRole);
        if(!result){
            return R.failed("修改失败");
        }
        return R.ok(oldRole);
    }

    /**
     * 删除,批量删除
     * @param roleIdArray
     * @return
     */
    @DeleteMapping("/delete")
    @ResponseBody
    public R<?> delete(HttpServletRequest request){
        String [] strArray = request.getParameterValues("roleIdArray[]");
        int [] roleIdArray = new int[strArray.length];
        for(int i = 0; i < strArray.length; i += 1){
            roleIdArray[i] = Integer.parseInt(strArray[i]);
        }
        R result  = roleService.deleteRolePermission(roleIdArray);
        if(result.getCode() == 0){
            return R.ok(null);
        }else{
            return R.failed(result.getMsg());
        }
    }

    /**
     * 获取角色权限权限列表
     * @return
     * 权限树结构
     * 带有角色是否有此权限的标识
     * 有标识就选中
     */
    @GetMapping("list_permission/{roleId}")
    @ResponseBody
    public List<PermissionVO> listPermissionByRoleId(@PathVariable("roleId") Integer roleId){
//        LayerTableVO<PermissionVO> vo = new LayerTableVO<>();
//        vo.setCode(0);
//        vo.setMsg("");
//        vo.setData(roleService.listPermissionByRoleId(roleId));
//        vo.setCount((long)vo.getData().size());
        return roleService.listPermissionByRoleId(roleId);
    }


    /**
     * 设置, 更新角色权限
     * @param roleId
     * @param permissionArray
     * @return
     */
    @PutMapping("/update_permission")
    @ResponseBody
    public R<?> updatePermissionByRoleId(HttpServletRequest request, Integer roleId){
        if(roleId == null){
            return R.failed("角色不能为空");
        }
        String [] strArray = request.getParameterValues("permissionArray[]");
        int[] permissionArray = null;
        if(strArray == null){
            permissionArray = new int[0];
        }else{
            permissionArray = new int[strArray.length];
        }
        for(int i = 0; i < strArray.length; i += 1){
            permissionArray[i] = Integer.parseInt(strArray[i]);
        }

        R<?> r = roleService.updatePermissionByRoleId(roleId, permissionArray);
        if(r.getCode() == 0){
            return R.ok(null);
        }else{
            return R.failed(r.getMsg());
        }
    }
}